import axios from "axios";
import { ElMessage, ElMessageBox } from "element-plus";
// import store from "store/index";

//api返回成功Code
const SuccessCode = ["100"];
//token过期返回Code
const RefreshCode = ["102"];
//非法Code
const IllegalCode = [];

// 创建axios实例
const service = axios.create({
  // 在请求地址前面加上baseURL
  baseURL: import.meta.env.VITE_BASE_API,
  // 当发送跨域请求时携带cookie
  // withCredentials: true,
  timeout: 5000,
});

// 请求拦截
service.interceptors.request.use(
  (config) => {
    // 指定请求令牌
    // config.headers["X-Token"] = "token-xxxxxx";
    return config;
  },
  (error) => {
    // 请求错误的统一处理
    console.log(error); // for debug
    return Promise.reject(error);
  }
);

// 响应拦截器
service.interceptors.response.use(
  /**
   * 通过判断状态码统一处理响应，根据情况修改
   * 同时也可以通过HTTP状态码判断请求结果
   */
  (response) => {
    const res = response.data;
    const responseCode = res.result_code;
    const responseMessage = res.result_msg;
    if (SuccessCode.indexOf(responseCode) >= 0) {
      return res;
    } else {
      ElMessage.error({
        message: responseMessage || "Error",
        duration: 5 * 1000,
      });

      if (RefreshCode.indexOf(responseCode) >= 0) {
        // token过期 重新登录
        ElMessageBox.confirm("您已登出, 请重新登录", "确认", {
          confirmButtonText: "重新登录",
          cancelButtonText: "取消",
          type: "warning",
        }).then(() => {
          //删除token操作
        });
      }
      return Promise.reject(res)
    }
  },
  (error) => {
    console.log("err" + error); // for debug
    ElMessage({
      message: responseMessage,
      type: "error",
      duration: 5 * 1000,
    });
    return Promise.reject(error);
  }
);

export default service;
